#
#   application.py
#   journalismManger
#
#   Created by luoxh on 2019-07-23-15:01.
#   Copyright © 2019 luoxh. All rights reserved.
#
from flask import request
from flask_api import FlaskAPI
from flask_cors import CORS
from flask_session import Session

from src.config import BaseConfig, DevConfig
from src.controller import all_blueprints, base_blueprints
from src.extension import all_plugins


class Application(FlaskAPI):

    def __init__(self, config_class: BaseConfig.__subclasses__() = None):
        if not config_class: config_class = DevConfig
        super().__init__(config_class.APP_NAME, static_folder=config_class.STATIC_DIRS,
                         template_folder=config_class.TEMPLATE_DIRS)
        self.config.from_object(config_class)
        CORS(self, supports_credentials=True)
        Session(self)
        for blueprint in all_blueprints: self.register_blueprint(blueprint)
        for blueprint in base_blueprints: self.register_blueprint(blueprint)
        for plugin in all_plugins: plugin.init_app(self)

    def handle_api_exception(self, exc):
        content = {'code': exc.code, 'msg': exc.msg, 'request': request.method + ' ' + self.get_url_no_param()}
        status = exc.status_code

        return self.response_class(content, status=status)

    @staticmethod
    def get_url_no_param():
        full_path = str(request.full_path)
        main_path = full_path.split('?')
        return main_path[0]
